package cn.diancan.action.manager;

import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

import cn.diancan.action.BaseAction;
import cn.diancan.exception.OutMsgException;
import cn.diancan.manager.security.ManagerAuth;
import cn.diancan.model.SysAuthority;
import cn.diancan.model.SysRole;
import cn.diancan.util.DateUtil;
import cn.diancan.vo.AuthorityVo;
import cn.diancan.vo.SysAuthorityVo;

import com.alibaba.fastjson.JSONObject;
import com.opensymphony.xwork2.ModelDriven;


public class AuthorityAction extends BaseAction implements ModelDriven<AuthorityVo>{
	private static final long serialVersionUID = 1L;
	
	private AuthorityVo requestVo=new AuthorityVo();
	
	
	
	/**
	 * 权限列表
	 */
	@ManagerAuth
	public String authorityList(){
	    
		//查询列表时，更新权限数据
		refreshMenu();
		return freemarkView("/views/ftl/manager/authority/authority_edit.ftl");
	}
	 
	
	/**
	 * 设置权限界面
	 * @return
	 */
	@ManagerAuth
	public String setAuthorityUI(){
		List<SysAuthority> list=sysAuthorityService.findTopList();
		getRequest().setAttribute("list", list);
		SysRole role = null;
		try {
			role = sysRoleService.findById(requestVo.getRoleId());
		} catch (OutMsgException e) {
			e.printStackTrace();
		}
		getRequest().setAttribute("role", role);
		String resourceIdList="";
		if (null!=role.getYmAuthorities()) {
			for (SysAuthority bean : role.getYmAuthorities()) {
				resourceIdList+=bean.getId().toString()+",";
			}	
		}
		getRequest().setAttribute("resourceIdList", resourceIdList);

		return freemarkView("/views/ftl/manager/authority/authority_list.ftl");
	}
	
	/**
	 * 新增一级权限
	 */
	@ManagerAuth
	public String addAuthority() throws OutMsgException{
		Map<String,Object> result = new HashMap<String,Object>();
		try {
			sysAuthorityService.saveAuthority(new SysAuthority(null, requestVo.getName(), null));	
			result.put("success", true);  
		} catch (Exception e) {
			result.put("success", false); 
			result.put("errorMsg", e.getMessage());
		}
		return textString(JSONObject.toJSONString(result));	
	}
	
	/**
	 * 更新权限
	 */
	@ManagerAuth
	public String updateAuthority() throws OutMsgException{
		Map<String,Object> result = new HashMap<String,Object>();
		try {
			SysAuthority bAuthority=sysAuthorityService.findById(requestVo.getId());
			bAuthority.setName(requestVo.getName());
			bAuthority.setUrl(requestVo.getUrl());
			bAuthority.setModificationDate(DateUtil.currentDateTime());
			sysAuthorityService.saveAuthority(bAuthority);
			result.put("pid",bAuthority.getParent().getId().toString()); 
			result.put("success", true); 		
		} catch (Exception e) {
			result.put("success", false); 
			result.put("errorMsg", e.getMessage());
		}
		return textString(JSONObject.toJSONString(result));
	}
	
	/**
	 * 新增二级权限
	 */
	@ManagerAuth
	public String addAuthorityChild(){
		Map<String,Object> result = new HashMap<String,Object>();
		SysAuthority uAuthority;
		try {
			uAuthority = sysAuthorityService.findById(requestVo.getId());
			sysAuthorityService.saveAuthority(new SysAuthority(requestVo.getUrl(), requestVo.getName(), uAuthority));
			result.put("success", true);  
			result.put("pid",requestVo.getId()); 		
		} catch (OutMsgException e) {
			result.put("success", false);  
			result.put("errorMsg", e.getMessage());
		}catch (Exception e) {
			result.put("success", false);  
			result.put("errorMsg", e.getMessage());
		}
		return textString(JSONObject.toJSONString(result));	
	}
	
	/**
	 * 查找一级权限的所有二级权限
	 */
	@ManagerAuth
	public String  findAuthorityChild() {
		List<SysAuthorityVo> list;
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		try {
			list=sysAuthorityService.findTopChild(requestVo.getId());
	        jsonMap.put("total", list.size());
	        jsonMap.put("rows", list);
		} catch (OutMsgException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
		return textString(JSONObject.toJSONString(jsonMap));	
	}


	/**
	 * 删除权限
	 */
	@ManagerAuth
	public String DeleteAuthority(){
	
		Map<String,Object> result = new HashMap<String,Object>();
		try {
			String[] ids=requestVo.getIds().split(",");
			for (int i = 0; i < ids.length; i++) {
				if (!"".equals(ids[i])) {
				sysAuthorityService.delete(Long.valueOf(ids[i]));
				}
			}
			result.put("success", true);  
			
		} catch (Exception e) {
			result.put("success", false); 
			result.put("errorMsg", e.getMessage());
		} 
		return textString(JSONObject.toJSONString(result));	
	}
	
	/**
	 * 一级权限列表
	 */
	@ManagerAuth
    public String findByTop(){
    	List<SysAuthorityVo> topList=sysAuthorityService.findTopListBySql();
    	Map<String, Object> jsonMap = new HashMap<String, Object>();
        jsonMap.put("total", topList.size());
        jsonMap.put("rows", topList); 
        return textString(JSONObject.toJSONString(jsonMap));	
    }

	/**
	 * 设置权限
	 * @return
	 */
	@ManagerAuth
	public String setAuthority(){ 
		try {
		    	SysRole role = sysRoleService.findById(requestVo.getRoleId());
			role.setYmAuthorities(new HashSet<SysAuthority>(sysAuthorityService.findByIds(requestVo.getIds())));
			sysRoleService.saveRole(role);	
			return jsonSuccess("设置成功");
		}   catch (OutMsgException e) {
			return jsonError(e);
		}catch (Exception e) {
		    return jsonError(e);
		}
		
	}

	/**
	 * 排序上移
	 * @return
	 * @param id 父级id
	 * @param true 表示上移
	 */
	@ManagerAuth
	public String  setUp() {
		Map<String,Object> result = new HashMap<String,Object>();
		try {
			if (sysAuthorityService.updateIndex(true,requestVo.getPid(),requestVo.getId())) {
				result.put("success", true); 
			}
		} catch (OutMsgException e) {
			result.put("success", false); 
		}catch (Exception e) {
		    	result.put("success", false); 
		}
		return textString(JSONObject.toJSONString(result));	
	}
	
	/**
	 * 排序下移
	 * @return
	 */
	@ManagerAuth
	public String setDown() {
		Map<String,Object> result = new HashMap<String,Object>();
		try {
			if (sysAuthorityService.updateIndex(false,requestVo.getPid(),requestVo.getId())) {
				result.put("success", true); 
			}
		} catch (OutMsgException e) {
			result.put("success", false); 
		}catch(Exception e){
		    	result.put("success", false); 
		}
		return textString(JSONObject.toJSONString(result));	
	}
	@Override
	public AuthorityVo getModel() {
		return requestVo;
	}
	
	/**
	 * 更新application里面的菜单
	 */
	@ManagerAuth
	public void refreshMenu(){
		 List<SysAuthority> topList=sysAuthorityService.findTopList();
		 List<String> allAuthorityUrls=sysAuthorityService.findAllUrl();//所有权限链接
		 getApplication().setAttribute("topList", topList);
		 getApplication().setAttribute("allAuthorityUrls", allAuthorityUrls);
	}

}
